﻿using System;
using QFramework;
using UnityEngine;

namespace HareGame
{
    public class MonoBehaviour_Ex : MonoBehaviour
    {
        [Header("是否需要监听事件(不需要的建议关闭，降低不必要的性能消耗)")]
        [SerializeField]
        protected bool NeedRegisterEvent = true;

        protected ResLoader m_ResLoader = ResLoader.Allocate();//资源加载器

        private EventID[] _events;//监听事件

        protected virtual void Awake()
        {
            if (NeedRegisterEvent)
            {
                RegisterEvent();
                foreach (var v in _events)
                {
                    GameEntry.Event.Register(v, DoEvent);
                }
            }
        }

        /// <summary>
        /// 注册监听事件
        /// </summary>
        /// <returns></returns>
        private void RegisterEvent()
        {
            _events = new EventID[GameEntry.GM.EventLength];
            int index = 0;
            foreach (EventID ID in Enum.GetValues(typeof(EventID)))
            {
                _events[index] = ID;
                index++;
            }
        }

        void DoEvent(int key, params object[] param)
        {
            if (!gameObject.activeInHierarchy)
                return;

            DoEvent((EventID)key, param);
        }

        /// <summary>
        /// 执行事件
        /// </summary>
        /// <param name="eventID">事件ID</param>
        /// <param name="param">参数</param>
        protected virtual void DoEvent(EventID eventID, params object[] param)
        {

        }

        protected virtual void OnDestroy()
        {
            if (m_ResLoader != null)
            {
                m_ResLoader.Recycle2Cache();
                m_ResLoader = null;
            }

            if (NeedRegisterEvent)
            {
                foreach (var v in _events)
                {
                    GameEntry.Event.UnRegister(v, DoEvent);
                }
            }
        }
    }
}